package com.five.calendar.function.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.five.calendar.ApplicationHelper;
import com.five.calendar.R;
import com.five.calendar.common.observer.Observer;
import com.five.calendar.database.bean.ScheduleBean;
import com.five.calendar.database.bean.TargetBean;
import com.five.calendar.database.bean.TargetDayBean;
import com.five.calendar.database.observer.TargetDayObservable;
import com.five.calendar.ui.activity.GoalDoneShowActivity;
import com.five.calendar.ui.activity.ScheduleAddActivity;
import com.five.calendar.ui.calendarview.model.CalendarDate;
import com.five.calendar.utils.TimeUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * HomeFragment用此Adapter
 */
public class ScheduleRecyclerAdapter extends RecyclerView.Adapter<ScheduleRecyclerAdapter.AbsViewHolder> {
    private static final int ITEM_TYPE_HEADER = 0;
    private static final int ITEM_TYPE_FIRST = 1;
    private static final int ITEM_TYPE_MIDDLE = 2;
    private static final int ITEM_TYPE_LAST = 3;
    private static final int ITEM_TYPE_GOAL = 4;
    private int[] mItemBgResources = new int[]{R.drawable.calendar_round_corner_bg1, R.drawable.calendar_round_corner_bg2, R.drawable.calendar_round_corner_bg3, R.drawable.calendar_round_corner_bg4};

    private Context mContext;
    private LayoutInflater mInflater;
    private List<ScheduleBean> mList;
    private List<TargetBean> mTargetList;
    private CalendarDate mCalendarDate;
    private String[] mTimes;

    public ScheduleRecyclerAdapter(Context context, List<ScheduleBean> list, List<TargetBean> targetList, CalendarDate calendarDate) {
        mContext = context;
        mInflater = LayoutInflater.from(mContext);
        mList = list;
        mTargetList = targetList;
        mCalendarDate = calendarDate;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return ITEM_TYPE_HEADER;
        } else if (position == 1 && mList.size() >= 1) {
            return ITEM_TYPE_FIRST;
        } else if (position == mList.size()) {
            return ITEM_TYPE_LAST;
        } else if (position > 1 && position < mList.size()){
            return ITEM_TYPE_MIDDLE;
        } else if (position == mList.size() + 1){
            return ITEM_TYPE_HEADER;
        } else {
            return ITEM_TYPE_GOAL;
        }
    }

    @Override
    public ScheduleRecyclerAdapter.AbsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case ITEM_TYPE_HEADER:
                return new HeaderViewHolder(mInflater.inflate(R.layout.calendar_home_recycler_header, parent, false));
            case ITEM_TYPE_FIRST:
                return new ItemViewHolder(mInflater.inflate(R.layout.calendar_home_recycler_item_first, parent, false));
            case ITEM_TYPE_LAST:
                return new ItemViewHolder(mInflater.inflate(R.layout.calendar_home_recycler_item_last, parent, false));
            case ITEM_TYPE_GOAL:
                return new ItemViewHolder(mInflater.inflate(R.layout.goal_item_layout, parent, false));
            default:
                return new ItemViewHolder(mInflater.inflate(R.layout.calendar_home_recycler_item_middle, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(AbsViewHolder holder, final int position) {
        if(position > 0 && position <= mList.size()) {
            ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
            itemViewHolder.mStartTime.setText(TimeUtils.timeFormatString(mList.get(position - 1).startTime));
            itemViewHolder.mEndTime.setText(TimeUtils.timeFormatString(mList.get(position - 1).endTime));
            itemViewHolder.mTitle.setText(mList.get(position - 1).title);
            itemViewHolder.mContent.setText(mList.get(position - 1).note);
            itemViewHolder.mBgLayout.setBackgroundResource(mItemBgResources[mList.get(position - 1).importance]);
            itemViewHolder.mBgLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ScheduleAddActivity.startScheduleAddActivity(mList.get(position - 1));
                }
            });
        } else if (position > 0 && position != mList.size() + 1) {
            final ItemViewHolder goalItemViewHolder = (ItemViewHolder) holder;
            goalItemViewHolder.mTitle.setText(mTargetList.get(position - mList.size() - 2).title);
            goalItemViewHolder.mContent.setText(TimeUtils.timeFromCreateTime(mTargetList.get(position - mList.size() - 2).endTime));
            TargetDayObservable.queryTargetByTargetId(mTargetList.get(position - mList.size() - 2).id).registerObserver(new Observer<TargetDayBean, Integer, List<TargetDayBean>>() {
                boolean isComplete = false;
                @Override
                public void onFail(Integer integer) {

                }

                @Override
                public void onComplete(final List<TargetDayBean> targetDayBeen) {
                    isComplete = false;
                    if (targetDayBeen != null){
                        for (final TargetDayBean tdb : targetDayBeen){
                            if (tdb.time.equals(mCalendarDate.toString())) {
                                TargetDayBean targetDay = tdb;
                                Log.e("ZXX","targetDay.id: " + targetDay.id);
                                isComplete = true;
                                goalItemViewHolder.mCheckIcon.setImageResource(R.drawable.ic_gals_done);
                                goalItemViewHolder.mCheckIcon.setOnClickListener(new DeleteListener(targetDay, goalItemViewHolder));
                            }
                        }
                        if(isComplete){
                            return;
                        }
                    }
                    if(isComplete == false) {
                        goalItemViewHolder.mCheckIcon.setImageResource(R.drawable.ic_goals_progress);
                        goalItemViewHolder.mCheckIcon.setOnClickListener(new SaveListener(mTargetList.get(position - mList.size() - 2).id, goalItemViewHolder));
                    }
                }
                @Override
                public void onSuccess(TargetDayBean targetDayBean) {

                }
            }).startDataHandle();
            goalItemViewHolder.mBgLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TargetDayObservable.queryTargetByTargetId(mTargetList.get(position - mList.size() - 2).id).registerObserver(new Observer<TargetDayBean, Integer, List<TargetDayBean>>() {
                        @Override
                        public void onFail(Integer integer) {

                        }

                        @Override
                        public void onComplete(List<TargetDayBean> targetDayBeen) {
                            Intent intent =  new Intent(ApplicationHelper.getContext(), GoalDoneShowActivity.class);
                            Bundle bundle = new Bundle();
                            if (targetDayBeen != null){
                                mTimes = new String[targetDayBeen.size()];
                                for (int i = 0; i < targetDayBeen.size(); i++){
                                    mTimes[i] = targetDayBeen.get(i).time;
                                }
                            } else {
                                mTimes = null;
                            }
                            bundle.putStringArray("times", mTimes);
                            bundle.putSerializable("targetbean", mTargetList.get(position - mList.size() - 2));
                            intent.putExtras(bundle);
                            //注意传进来的context必须是activity
                            Activity activity = (Activity) mContext;
                            activity.startActivityForResult(intent, 2);
                        }

                        @Override
                        public void onSuccess(TargetDayBean targetDayBean) {

                        }
                    }).startDataHandle();
                }
            });
            goalItemViewHolder.mBgLayout.setBackgroundResource(mItemBgResources[1]);
        } else if (position == mList.size() + 1) {
            HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
            headerViewHolder.mHeader.setText("Goals");
        }
    }

    @Override
    public int getItemCount() {
        return mList.size() + mTargetList.size() + 2;
    }

    public static class AbsViewHolder extends RecyclerView.ViewHolder {
        public AbsViewHolder(View itemView) {
            super(itemView);
        }
    }

    public static class HeaderViewHolder extends AbsViewHolder {
        private TextView mHeader;
        public HeaderViewHolder(View view) {
            super(view);
            mHeader = (TextView) view.findViewById(R.id.recycler_item_header);
        }
    }

    public static class ItemViewHolder extends AbsViewHolder {
        private TextView mStartTime;
        private TextView mEndTime;
        private TextView mTitle;
        private TextView mContent;
        private LinearLayout mBgLayout;
        private ImageView mCheckIcon;

        public ItemViewHolder(View itemView) {
            super(itemView);
            mStartTime = (TextView) itemView.findViewById(R.id.recycler_item_start_time);
            mEndTime = (TextView) itemView.findViewById(R.id.recycler_item_end_time);
            mTitle = (TextView) itemView.findViewById(R.id.recycler_item_title);
            mContent = (TextView) itemView.findViewById(R.id.recycler_item_content);
            mBgLayout = (LinearLayout) itemView.findViewById(R.id.bg_layout);
            mCheckIcon = (ImageView) itemView.findViewById(R.id.goal_done);
        }
    }

    private class SaveListener implements View.OnClickListener {
        private long mTargetId;
        private ItemViewHolder goalItemViewHolder;
        public SaveListener(long mTargetId, ItemViewHolder goalItemViewHolder){
            this.mTargetId = mTargetId;
            this.goalItemViewHolder = goalItemViewHolder;
        }

        @Override
        public void onClick(View v) {
            String dates = mCalendarDate.toString();
            TargetDayObservable.saveTarget(mTargetId, dates).registerObserver(new Observer<TargetDayBean, Integer, List<TargetDayBean>>() {
                @Override
                public void onFail(Integer integer) {
                }

                @Override
                public void onComplete(List<TargetDayBean> targetDayBeen) {
                }

                @Override
                public void onSuccess(TargetDayBean targetDayBean) {
                    Toast.makeText(ApplicationHelper.getContext(), "save successfully", Toast.LENGTH_SHORT).show();
                    goalItemViewHolder.mCheckIcon.setImageResource(R.drawable.ic_gals_done);
                    goalItemViewHolder.mCheckIcon.setOnClickListener(new DeleteListener(targetDayBean, goalItemViewHolder));
                    Log.e("ZXX","save targetDaybean.id: "+ targetDayBean.id);
                }
            }).startDataHandle();
        }
    }

    private class DeleteListener implements View.OnClickListener{
        private TargetDayBean mTargetDayBean;
        private ItemViewHolder goalItemViewHolder;
        public DeleteListener(TargetDayBean targetDayBean, ItemViewHolder goalItemViewHolder){
            this.mTargetDayBean = targetDayBean;
            this.goalItemViewHolder = goalItemViewHolder;
        }

        @Override
        public void onClick(View v) {
            ArrayList targetDayBeans = new ArrayList();
            targetDayBeans.add(mTargetDayBean);
            TargetDayObservable.deleteTarget(targetDayBeans).registerObserver(new Observer<TargetDayBean, Integer, List<TargetDayBean>>() {
                @Override
                public void onFail(Integer integer) {

                }

                @Override
                public void onComplete(List<TargetDayBean> targetDayBeen) {
                    goalItemViewHolder.mCheckIcon.setImageResource(R.drawable.ic_goals_progress);
                    goalItemViewHolder.mCheckIcon.setOnClickListener(new SaveListener(mTargetDayBean.targetId, goalItemViewHolder));
                }

                @Override
                public void onSuccess(TargetDayBean targetDayBean) {
                    Log.e("ZXX", "delete targetDayBean.Id" + targetDayBean.id);
                }
            }).startDataHandle();
        }
    }
}
